package edu.ilstu.mind.ise.ccp.logger.gui;

import edu.ilstu.mind.ise.ccp.logger.AbstractLogger;
import edu.ilstu.mind.ise.ccp.logger.LoggerLevel;

class GuiLogger extends AbstractLogger {

	private final TextWriter writer;
	private final TextWriter errorWriter;
	
	public GuiLogger(TextWriter writer, TextWriter errorWriter, String name, LoggerLevel level) {
		super(name, level);
		this.writer = writer;
		this.errorWriter = errorWriter;
	}

	@Override
	public synchronized void trace(String message) {
		log(LoggerLevel.TRACE, message);
	}

	@Override
	public synchronized void debug(String message) {
		log(LoggerLevel.DEBUG, message);
	}

	@Override
	public synchronized void info(String message) {
		log(LoggerLevel.INFO, message);
	}

	@Override
	public void warn(String message) {
		log(LoggerLevel.WARN, message);
	}

	@Override
	public void warn(String message, Throwable t) {
		log(LoggerLevel.WARN, message, t);
	}

	@Override
	public void error(String message) {
		log(LoggerLevel.ERROR, message);
	}

	@Override
	public void error(String message, Throwable t) {
		log(LoggerLevel.WARN, message, t);
	}

	@Override
	public void fatal(String message) {
		log(LoggerLevel.FATAL, message);
	}

	@Override
	public void fatal(String message, Throwable t) {
		log(LoggerLevel.WARN, message, t);
	}
	
	private synchronized void log(LoggerLevel level, String message) {
		if(isEnabled(level)) {
			String text = level + " " + getTimestamp() + " " + message + "\n";
			writer.write(text);
			if(level.isLoggable(LoggerLevel.ERROR)) {
				errorWriter.write(text);
			}
		}
	}
	
	private synchronized void log(LoggerLevel level, String message, Throwable t) {
		if(isEnabled(level)) {
			String text = level + " " + getTimestamp() + " " + message + "\n" + getThrowableAsString(t) + "\n";
			writer.write(text);
			if(level.isLoggable(LoggerLevel.ERROR)) {
				errorWriter.write(text);
			}
		}
	}

}
